package com.ztn.iot.zhonghaichi.fun;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ztn.base.util.common.HttpClientTool;
import com.ztn.base.util.common.ImageTool;
import com.ztn.base.util.common.JsonTool;
import com.ztn.base.util.common.TimeTool;
import com.ztn.iot.zhonghaichi.entity.SiteEntity;
import com.ztn.iot.zhonghaichi.properties.ZhcProperties;
import com.ztn.iot.zhonghaichi.push.CameraPushApi;
import com.ztn.iot.zhonghaichi.service.IIotDeviceService;
import com.ztn.iot.zhonghaichi.service.ISiteService;
import com.ztn.iot.zhonghaichi.util.LocalFileUtilImpl;
import com.ztn.sdk.iot.api.res.BaseRes;
import com.ztn.sdk.iot.api.util.HttpTool;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Slf4j
@EnableScheduling
@Component
public class CameraFun {

    @Autowired
    private CameraPushApi cameraPushApi;

    @Autowired
    private LocalFileUtilImpl localFileUtil;

    @Autowired
    private IIotDeviceService iotDeviceService;

    @Autowired
    private ISiteService siteService;

    @Autowired
    private ZhcProperties zhcProperties;

//    @PostConstruct
//    public void init() {
//        pushPicture();
//    }


    @Scheduled(cron = "0 0 0/2 * * ? ")
    public void snap() {
        new Thread(() -> {
            pushPicture();
        }).start();

    }

    @Data
    public static class ListCameraReq {
        private String deviceCore;
    }

    @Data
    public static class Camera {

        private Integer cameraId;

        private String hid;

        private String port;
    }

    public void pushPicture() {
        log.info("开始抓拍");
        iotDeviceService.listAll().forEach(iotDeviceEntity -> {
            final SiteEntity siteEntity = siteService.get(iotDeviceEntity.getSiteId());
            if (null == siteEntity) {
                log.error("null == siteEntity {}", iotDeviceEntity.getSiteId());
                return;
            }
            ListCameraReq listCameraReq = new ListCameraReq();
            listCameraReq.setDeviceCore(iotDeviceEntity.getDeviceCore());
            BaseRes<List<Camera>> res = HttpTool.doPost("camera/bind/list", JsonTool.toJson(listCameraReq), new TypeReference<BaseRes<List<Camera>>>() {
            });
            if (null != res && null != res.data) {
                res.data.forEach(cam -> {
//                    if(!cam.getHid().equals("J14020593")){
//                        return;
//                    }
                    InputStream inputStream = null;
                    try {
                        String url = HttpTool.BASE_URL + "camera/snap?hid=" + cam.getHid() + "&access-token=" + HttpTool.token;
                        log.info("snap {}", url);
                        inputStream = HttpClientTool.getForStream(url, null);
                        if (null == inputStream) {
                            log.error("null == inputStream");
                            return;
                        }
                        byte[] snap = inputStream.readAllBytes();
                        if (null == snap || snap.length < 1000) {
                            if (null == snap) {
                                log.error("null == snap {} {}", cam.getHid(), cam.getPort());
                            } else {
                                log.error("snap error {} {} {}", cam.getHid(), cam.getPort(), new String(snap));
                            }
                            return;
                        }
                        if (null != zhcProperties.getSavePicture() && zhcProperties.getSavePicture()) {
                            localFileUtil.insert("camera", File.separator + "picture" + File.separator + siteEntity.getSiteCode() + File.separator + TimeTool.time() + ".png", snap);
                        }
                        String base64Str = ImageTool.encodeBytesToBase64(snap);
                        if (!StringUtils.hasText(base64Str)) {
                            log.error("!StringUtils.hasText(base64Str) {} {}", cam.getHid(), cam.getPort());
                        }
                        cameraPushApi.pushPicture(siteEntity.getSiteCode(), base64Str);
                        log.info("success push picture {}", siteEntity.getSiteCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (null != inputStream) {
                            try {
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            } else {
                log.error("get device camera list worry");
            }
        });
    }


}
